package com.study.mydemo.controller;


import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.excel.EasyExcel;
import com.study.mydemo.entity.UserEntity;
import com.study.mydemo.util.MyMergeStrategy;
import com.study.mydemo.util.WaterMarkHandler;
import com.study.mydemo.util.WaterMarkUtil;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ExportExcelController {

    private List<UserEntity> data() {
        List<UserEntity> list = new ArrayList<UserEntity>();
        for (int i = 0; i < 10; i++) {
            UserEntity data = new UserEntity();
            data.setName("张三" + i);
            data.setAge(i);
            data.setIdCard("445202" + i);
            list.add(data);
        }
        return list;
    }


    @GetMapping("/EasyExport")
    public void EasyExport(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("导出测试", "UTF-8");
        String name123 = URLEncoder.encode("导出测试", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), UserEntity.class)
                .inMemory(true) // 注意，此项配置不能少
                .registerWriteHandler(new WaterMarkHandler("我是水印"))
//                .registerWriteHandler(new MyMergeStrategy())
                .sheet("模板")
                .doWrite(data());
    }

    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {

        String[] fields1 = new String[]{"name","age","idcard"};
        String[] fields2 = new String[]{"uuid","name","age","idcard"};

        List<UserEntity> data = new ArrayList<>();
        UserEntity user = new UserEntity();
        user.setUuid("zs");
        user.setAge(18);
        user.setIdCard("445202199401010101");
        user.setName("张三");

        UserEntity user1 = new UserEntity();
        user.setUuid("ls");
        user1.setAge(28);
        user1.setIdCard("445202199401010101");
        user1.setName("李四");

        UserEntity user2 = new UserEntity();
        user.setUuid("ww");
        user2.setAge(38);
        user2.setIdCard("445202199802020201");
        user2.setName("王五");
        data.add(user);
        data.add(user1);
        data.add(user2);

        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("sheet1");
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short) 12);
        //设置字体加粗
        font.setBold(true);
        //给字体设置样式
        cellStyle.setFont(font);

        //创建标题行
        XSSFRow row = sheet.createRow(0);
        XSSFCell cell1 = row.createCell(0);
        cell1.setCellValue("广东省退役军人数据总览");

        //创建字段行
        row = sheet.createRow(1);
        for(int j = 0;j < fields1.length;j ++){
            Cell cell = row.createCell(j);
            cell.setCellValue(fields1[j]);
            cell.setCellStyle(cellStyle);

        }

        int rownum=0;
        for (int i = 0; i < data.size(); i++) {
            rownum++;
            XSSFRow dataRow1 = sheet.createRow(rownum);
            UserEntity data1 =data.get(i);
            //创建idcell
            XSSFCell idCell = row.createCell(0);
            idCell.setCellValue(user.getUuid());

            //创建namecell
            XSSFCell nameCell = row.createCell(1);
            nameCell.setCellValue(user.getName());

            //创建agecell
            XSSFCell addressCell = row.createCell(2);
            addressCell.setCellValue(user.getAge());
        }


        //合并首行单元格
        CellRangeAddress firstCellRangeAddress = new CellRangeAddress(0, 0, 0, fields1.length);
        sheet.addMergedRegion(firstCellRangeAddress);
        //合并尾行单元格
        CellRangeAddress cellRangeAddress = new CellRangeAddress(data.size(), data.size(), 0, fields1.length);
        sheet.addMergedRegion(cellRangeAddress);

        byte[] bytes = WaterMarkUtil.createWaterMark("我叫水印！").toByteArray();
        int i = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
        String rID = sheet.addRelation(null, XSSFRelation.IMAGES, workbook.getAllPictures().get(i)).getRelationship().getId();
        sheet.getCTWorksheet().addNewPicture().setId(rID);

        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String name = "TEST";
        response.setHeader("Content-Disposition","attachment;filename="+name+".xls");

        ServletOutputStream out= null;
        try {
            out = response.getOutputStream();
            workbook.write(out);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            workbook.close();
        }
        out.close();
    }

    private void getData(){

    }
}
